import {host,port} from "../configfile/config.js"
$(function() {
    const baseURL = "http://" + host + ":" + port
    const dbname = $(document).attr('title')
    $(".header .main li").on("click", function() {
        var path = $(this).attr("id")
        console.log(path);
        let url = baseURL+"/" + dbname + "/" + path
        $(location)[0].href = url
    })
// ------------------------------------------------------
    //发展趋势折线图 使用$.Deferred()实现同步请求
    function development() {
      let defer = $.Deferred()
          let chartdata
          let url = baseURL+"/development/chart"
          $.ajax({
              type:"GET",
              url:url,
              async:true,
              ContentType:'application/json',
              data:{
                  dbname:dbname
              },
              success:(res)=>{
                chartdata = res.chartdata
                defer.resolve(chartdata)
              }
          })
          return defer
  };
  // 发展趋势折线图
  (async ()=>{
    var mCharts = echarts.init($(".development-card .development-chart")[0],"vintage")
    mCharts.showLoading();
    $.when(development()).done((v)=>{
      let ssss
      ssss = v
      var xDataArr = ssss.xDataArr  
      let series = ssss.series
      let legend = ssss.legend
      let summary_text = ssss.text_data
      $(".summary-card .summary-text").html('<span class="text_span">“'+dbname+'”</span>事件，自<span class="text_span">'+summary_text["fromdate"]+'</span>至<span class="text_span">'+summary_text["savedate"]+'</span>期间，互联网上共监测到相关舆情<span class="text_span">'+summary_text["all"]+'</span>条。其中<span class="text_span">'+summary_text["max"][0]+'</span>声量最大，为<span class="text_span">'+summary_text["max"][1]+'</span>条。事件首发文章于<span class="text_span">'+summary_text["first"]+'</span>发布在<span class="text_span">'+summary_text["first-pingtai"]+'</span>，具体分析如下。')
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend:{
          data:legend
        },
        toolbox: {
          feature: {
            saveAsImage: {title:false}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: xDataArr
          }
        ],
        yAxis: [
          {
            splitLine: {
                show: false
            },
            type: 'value'
          }
        ],
        series
      };
      mCharts.setOption(option)
      mCharts.hideLoading();
    })
  })();
// ---------------------------------------------------

  // 词云图 使用promise实现请求的同步
  function wordcloud(){
    return new Promise((resolve, reject)=>{
      let chartdata
      let url = baseURL+"/wordcloud/cloud"
      $.ajax({
        type:"GET",
              url:url,
              async:true,
              ContentType:'application/json',
              data:{
                  dbname:dbname
              },
              success:(res)=>{
                if(res.status == 200){
                  resolve(res.chartdata)
                }
                else{
                  reject("暂无数据")
                }
              }
      })
    })
  }
  (async ()=>{
    var mCharts = echarts.init($(".wordcloud-card .wordcloud-chart")[0],"vintage")
    mCharts.showLoading();
    let JosnList = await wordcloud()
    let rows = []
    for(var i=0;i<10;i++){
      var row = '<tr>\
          <td class="order col-sm-3">'+(i+1)+'</td>\
          <td class="keyword col-sm-6">'+JosnList[i].name+'</td>\
          <td class="frequence col-sm-3">'+JosnList[i].value+'</td>\
        </tr>'
      rows.push(row)
    }
    $(".wordcloud-list .table tbody").append(rows.join(''))
    var textcolor = [
      "#d87c7c",
      "#919e8b",
      "#d7ab82",
      "#6e7074",
      "#61a0a8",
      "#efa18d",
      "#787464",
      "#cc7e63",
      "#724e58",
      "#4b565b"
    ]
    var option = {
        tooltip: {
            show: true
        },
        series: [{
            type: 'wordCloud',
            sizeRange: [10, 50],//文字范围
            rotationRange: [0, 0],
            //形状
            shape: 'circle',
            textStyle: {
                color: function() {//文字颜色的随机色
                    return textcolor[Math.floor(Math.random() * 10)]
                },
                //悬停上去的字体的阴影设置
                emphasis: {
                    shadowBlur: 10,
                    shadowColor: '#333'
                }
            },
            data: JosnList
        }]
    };
    mCharts.hideLoading();
    mCharts.setOption(option)
    
  })();
  // ----------------------------------------------

  // 微博用户认证类型
  let authorTableData
  function authentification(){
    return new Promise((resolve, reject)=>{
      let url = baseURL+"/authentification/pie"
      $.ajax({
        type:"GET",
              url:url,
              async:true,
              ContentType:'application/json',
              data:{
                  dbname:dbname
              },
              success:(res)=>{
                if(res.status == 200){
                  resolve(res.alldata)
                }
                else{
                  reject("暂无数据")
                }
              }
      })
    })
  }
  (async ()=>{
    var mCharts = echarts.init($(".authentification-card .authentification-pie")[0],"vintage")
    mCharts.showLoading();
    let a = await authentification()
    authorTableData = a.tabledata
    click_tab(1)
    let option = {
      tooltip: {
        trigger: 'item',
        formatter: "{a} <br/>{b} : {c} ({d}%)"
      },
      legend: {
        top: '5%',
        left: 'center'
      },
      
      series: [
        {
          name: '用户认证',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          data: a.chartData
        }
      ]
    };
    mCharts.setOption(option)
    mCharts.hideLoading();
  })();

  function click_tab(typeid){
    $(".authentification-tab .tab-box i").remove()
    $(".authentification-tab .tab-box").each(function(i,v){
      $(v).removeClass("active")
    })
    $("#type_"+typeid).addClass("active").prepend('<i class="linxing"></i>')
    let row = ""
    let authorType = "blue"
    if(typeid==0)authorType="orange"
    if(typeid==10)authorType="normal"
    $.each(authorTableData[String(typeid)],function(i,v){
      console.log("vvvv",v);
      row +='<div class="content-box">\
              <div class="photo" style="flex: 3;margin-right: 10px;">\
                  <img src="../static/img/photo.png" alt="出错了" style="width:100%">\
              </div>\
              <div class="others" style="flex: 7;">\
                  <div class="author" style="width:100%;line-height: 30px;height: 30px;font-size: 16px;position: relative;">\
                      <span style="display: inline-block;max-width:80%;height: 30px;overflow: hidden;">'+v[0]+'</span>\
                      <img src="../static/img/'+authorType+'.png" alt="4" style="margin-left: 4px;position: absolute;width: 12px;top: 0.8rem;">\
                  </div>\
                  <div class="author_message">\
                      <div class="fans">粉丝：<span>'+v[1]["fans"]+'</span></div>\
                      <div class="pub">发文：<span>'+v[1]["pub"]+'</span></div>\
                  </div>\
              </div>\
            </div>\
          '
    })
    $(".authentification-list").empty().append(row)
  }

  $(".authentification-tab .tab-box").on("click",function(e){
    let typeid = parseInt($(this).attr("id").split("_")[1])
    click_tab(typeid)
  })

  // 微博用户认证类型end
  
  // 地图
  function map(){
    return new Promise((resolve,reject)=>{
      let url = baseURL+"/map"
      $.ajax({
          type:"GET",
              url:url,
              async:true,
              ContentType:'application/json',
              data:{
                  dbname:dbname
              },
              success:(res)=>{
                  if(res.status == 200){
                  resolve(res.data)
                  }
                  else{
                  reject("暂无数据")
                  }
              }
        })
      })
  }

  (async()=>{
    var chart = echarts.init(document.getElementById('echarts-amap'),"vintage");
    chart.showLoading();
    var data = await map();
    let max_len = data.length > 5 ? data.slice(0,5): data.length
    let i = 0
    let rows = []
    let row = ""
    let max_data = -Infinity
    let min_data = Infinity
    for(;i<data.length;i++){
      if(i <= 4){
        row = '<span class="text_span">'+data[i].name+'</span>'
        rows.push(row)
      }
      if(data[i].value > max_data)max_data = data[i].value
      if(data[i].value < min_data)min_data = data[i].value
    }
    console.log(max_data,min_data);
    $(".location-card .location-text").html('该事件的传播者、关注者主要集中在'+rows.join("、")+'等地区')
    rows = []
    for(i=0;i<data.length;i++){
      if(i>9)break
      row = '<tr>\
          <td class="order col-sm-3">'+(i+1)+'</td>\
          <td class="keyword col-sm-6">'+data[i].name+'</td>\
          <td class="frequence col-sm-3">'+data[i].value+'</td>\
        </tr>'
      rows.push(row)
    }
    $(".location-list .table tbody").append(rows.join(''))
    
    var geoCoordMap={
        '山东':[117.000923, 36.675807],
    '河北':[115.48333,38.03333],
    '吉林':[125.35000,43.88333],
    '黑龙江':[127.63333,47.75000],
    '辽宁':[123.38333,41.80000],
    '内蒙古':[111.670801, 41.818311],
    '新疆':[87.68333,43.76667],
    '甘肃':[103.73333,36.03333],
    '宁夏':[106.26667,37.46667],
    '山西':[112.53333,37.86667],
    '陕西':[108.95000,34.26667],
    '河南':[113.65000,34.76667],
    '安徽':[117.283042, 31.86119],
    '江苏':[119.78333,32.05000],
    '浙江':[120.20000,30.26667],
    '福建':[118.30000,26.08333],
    '广东':[113.23333,23.16667],
    '江西':[115.90000,28.68333],
    '海南':[110.35000,20.01667],
    '广西':[108.320004, 22.82402],
    '贵州':[106.71667,26.56667],
    '湖南':[113.00000,28.21667],
    '湖北':[114.298572, 30.584355],
    '四川':[104.06667,30.66667],
    '云南':[102.73333,25.05000],
    '西藏':[91.00000,30.60000],
    '青海':[96.75000,36.56667],
    '天津':[117.20000,39.13333],
    '上海':[121.55333,31.20000],
    '重庆':[106.45000, 29.56667],
    '北京': [116.41667,39.91667],
    '台湾': [121.30, 25.03],
    '香港': [114.10000,22.20000],
    '澳门': [113.50000,22.20000],
    }
    var convertData = function (data) {
      var res = [];
      for (var i = 0; i < data.length; i++) {
          var geoCoord = geoCoordMap[data[i].name];
          if (geoCoord) {
            res.push({
                name: data[i].name,
                value: geoCoord.concat(data[i].value)
            });
          }
      }
      return res;
      };
    var textcolor = [
        "#d87c7c",
        "#919e8b",
        "#d7ab82",
        "#6e7074",
        "#61a0a8",
        "#efa18d",
        "#787464",
        "#cc7e63",
        "#724e58",
        "#4b565b"
    ]
    var option = {
    amap: {
        viewMode: '3D',
        center: [108.39, 39.9],
        zoom: 4,
        resizeEnable: true,
        mapStyle: 'amap://styles/whitesmoke',
        renderOnMoving: true,
        echartsLayerZIndex: 2000,
        echartsLayerInteractive: true,
        largeMode: false
    },
    tooltip : {
        trigger: 'item'
    },
    animation: true,
    series: [
          {
            name: '分布',
            type: 'scatter',
            coordinateSystem: 'amap',
            data: convertData(data),
            symbolSize: function (val) {
                return 80*val[2]/(max_data-min_data);
            },
            encode: {
                value: 2
            },
            label: {
                formatter: '{b}',
                position: 'right',
                show: false
            },
            itemStyle: {
                // color: '#00c1de'
                color: function(val){
                    return textcolor[Math.floor(Math.random() * 10)]
                }
            },
            emphasis: {
                label: {
                show: true
                }
            }
          }
        ]
    };
    chart.hideLoading();
    chart.setOption(option);
    // get AMap extension component
    var amapComponent = chart.getModel().getComponent('amap');
    // get the instance of AMap
    var amap = amapComponent.getAMap();
    // operations below are the same as amap
    amap.addControl(new AMap.Scale());
    amap.addControl(new AMap.ToolBar());

  })();
  // 地图end
  


  // 微博类型
  function TypeOfWeibo() {
      return new Promise((resolve,reject)=>{
          let url = baseURL+"/typeofweibo"
          $.ajax({
              type:"GET",
                  url:url,
                  async:true,
                  ContentType:'application/json',
                  data:{
                      dbname:dbname
                  },
                  success:(res)=>{
                      if(res.status == 200){
                        resolve(res.data)
                      }
                      else{
                        reject("暂无数据")
                      }
                  }
          })
      })
  };

  (async ()=>{
      var mCharts = echarts.init($(".weibotype-card .weibotype-chart")[0],"vintage")
      var mPie = echarts.init($(".weibotype-card .weibotype-pie")[0],"vintage")
      mPie.showLoading();
      mCharts.showLoading();
      let respone = await TypeOfWeibo()
      let textcontent = respone["textdata"]
      $(".weibotype-card .weibotype-text").html('事件相关博文信息量在<span class="text_span">'+textcontent["max_index"]+'</span>达到最高峰，\
                                                共产生<span class="text_span">'+textcontent["all"]+'</span>篇相关信息。<span class="text_span">'+textcontent["original"]+'%</span>的网民针对该话题发表了原创观点，\
                                                为事件的发展提供舆论导向，<span class="text_span">'+textcontent["Retweets"]+'%</span>的网民转载了原帖信息，\
                                                推动了舆论在网民中的传播，增强了话题的影响效果，使该事件的传播热度不断升温；另外<span class="text_span">'+textcontent["Comments"]+'%</span>的网民评论了以上博文。')
      let ssss
      ssss = respone["chartdata"]
      var xDataArr = ssss.xDataArr  
      let series = ssss.series
      console.log(series);
      let legend = ssss.legend
      let option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend:{
          data:legend
        },
        toolbox: {
          feature: {
            saveAsImage: {title:false}
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            data: xDataArr
          }
        ],
        yAxis: [
          {
            splitLine: {
                show: false
            },
            type: 'value'
          }
        ],
        series
      };
      mCharts.setOption(option)
      mCharts.hideLoading();

      
      let piedata = respone["piedata"]
      let Pieoption = {
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          top: '5%',
          left: 'center'
        },
        
        series: [
          {
            name: '微博类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            data: piedata
          }
        ]
      };
      mPie.setOption(Pieoption)
      mPie.hideLoading();
  })();
  // 微博类型end
})